<template>
  <div class="common-layout" style="height:100%">
    <el-container style="height:100%">
      <el-header>
        <div class="sa-title sa-flex sa-row-between">
          <div class="label sa-flex">
            <span class="left">新增服务</span>
          </div>
        </div>
      </el-header>
      <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" label-position="left" label-width="130px">
        <el-form-item label="服务名称" prop="type_name">
          <el-input v-model="form.model.type_name" placeholder="请输入服务名称"></el-input>
        </el-form-item>
        <el-form-item label="服务主图" prop="icon_url">
          <div class="sa-flex sa-col-bottom ">
            <sa-uploader v-model="form.model.icon_url" fileType="image" size="100"></sa-uploader>
            <div class="sa-p-l-15">
              上传服务图片
            </div>
          </div>
        </el-form-item>
        <el-form-item label="服务分类" prop="parent_id">
          <el-select v-model="form.model.parent_id" placeholder="请选择服务分类" >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.type_name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remake">
          <el-input
            v-model="form.model.remake"
            :autosize="{ minRows: 4, maxRows: 6 }"
            type="textarea"
            placeholder="请输入备注"
          />
        </el-form-item>
        <el-form-item label="服务项目/规格" prop="service" label-position="top">
          <div class="service-addbtn" >
            <el-button  v-auth="'seller.admin.service.setservice'" style="width: 125px;height: 35px;border-radius: 20px;background: #806AF6;color:#fff" @click="addfirst">添加项目</el-button>
          </div>
          <div style="overflow: auto">
            <div class="custom-tree-header sa-flex">
              <div class="custom-tree-box sa-flex">
                <div class="expanded-width-txm">条形码</div>
                <div class="expanded-width-xm">
                  <span style="color:#ff4d4f">*</span>
                  服务项目/规格名称
                </div>
                <div class="expanded-width-pym">拼音码</div>
                <div class="expanded-width-lsj">
                  <span style="color:#ff4d4f">*</span>零售价（元）</div>
                <div class="expanded-width-hyj">会员价（元）</div>
                <div class="expanded-width-des">服务时长</div>
                <div class="expanded-width-sort">副含商品</div>
                <div class="expanded-width-operation">操作</div>
              </div>
            </div>
            <div class="sa-tree-table-content sa-flex">
              <el-tree :data="form.model.service" ref="treeRef" node-key="tree_id" default-expand-all :expand-on-click-node="false"
                :props="defaultProps">
                <template #default="{ node, data }">
                  <div class="sa-flex drag-item" v-if="!(data.deleted && data.deleted == 1)">
                    <div class="expanded-width-txm">
                        <div><el-input v-model="data.bar_code" type="number" placeholder="请输入条形码" /></div>
                    </div>
                    <div class="expanded-width-xm">
                      <div> <el-input v-model="data.service_name" placeholder="请输入服务项目名称" /> </div>
                    </div>
                    <div class="expanded-width-pym">
                        <div><el-input v-model="data.service_code" type="text"  placeholder="请输入拼音码" /></div>
                    </div>
                    <div class="expanded-width-lsj">
                      <div><el-input v-model="data.retail_price"type="number"  style="width: 150px" placeholder="请输入零售价" /></div>
                    </div>
                    <div class="expanded-width-hyj">
                        <div><el-input v-model="data.vip_price"type="number"  style="width: 150px" placeholder="请输入会员价" /></div>
                    </div>
                    <div class="expanded-width-des">
                      <div><el-select v-model="data.service_time"  style="width: 150px" placeholder="请选择服务时长" >
                        <el-option
                          v-for="item in timeOptions"
                          :key="item.value"
                          :label="item.name"
                          :value="item.value"
                        />
                      </el-select></div>
                    </div>
                    <div class="expanded-width-sort" style="height: 100%">
                      <div class="sa-flex-col sa-row-between " style="height: 80%" >
                        <el-button type="primary" v-auth="'seller.admin.service.selgoods'" @click="addGoods(data)">选择商品</el-button>
                        <el-button type="primary" v-auth="'seller.admin.service.selgoods'" @click="lookGoods(data)">查看已选</el-button>
                      </div>
                    </div>
                    <div class="expanded-width-operation" >
                      <span @click="remove(node, data)" style="color: #ff4d4f" v-auth="'seller.admin.service.delgoods'">删除</span>
                    </div>
                  </div>
                </template>
              </el-tree>
            </div>
          </div>
        </el-form-item>
      </el-form>
      </el-main>
      <sa-view-bar>
        <template #left>
        </template>
        <template #right>
          <div class="sa-p-10 sa-p-r-60">
            <el-popconfirm
              width="220"
              confirm-button-text="确认返回"
              cancel-button-text="取消"
              title="返回将清楚已修改数据！是否确认返回？"
              @confirm="router.back()"
            >
              <template #reference>
                <el-button style="margin-right:20px">返回</el-button>
              </template>
            </el-popconfirm>
            <el-button v-auth="'seller.admin.service.setservice'" type="primary" @click="confirm">{{route.query.type=='add' ? '提交':'保存'}}
            </el-button>
          </div>
        </template>
      </sa-view-bar>
    </el-container>
  </div>
</template>

<script setup>
import { onMounted, reactive, ref,unref } from 'vue';
import { api } from './service.service';
import { useModal, usePagination } from '@/sheep/hooks';
import { useSearch } from '@/sheep/components/sa-table/sa-search/useSearch';
import { composeFilter } from '@/sheep/utils';
import { cloneDeep } from 'lodash';
import {ElMessage } from 'element-plus';
import GoodsSelect from '@/app/shop/admin/goods/goods/select.vue';

import selectLook from './select.vue';
// import serviceEdit from './service/index.vue';
import { useRoute,useRouter } from 'vue-router';

const route = useRoute();
const router = useRouter();
const timeOptions = []
let timesArr = [1,2,3,4,5,6,7,8]
timesArr.forEach(t => {
  timeOptions.push({
    value:Number(t - 0.5),
    name:(t - 0.5) + '小时'
  },{
    value:Number(t),
    name:t + '小时'
  })
})
const options = ref([])

onMounted(() => {
  if(route.query.type == 'add'){
    form.model.parent_id = Number(route.query.id)
  }else{
    getService()
  }
  getTypeList()
})
// 添加 编辑 form
let formRef = ref(null);
const form = reactive({
  model: {
    type_name: '',
    icon_url: '',
    parent_id: '',
    remake: '',
    service: [],
  },
  rules: {
    type_name: [{ required: true, message: '请输入服务名称', trigger: 'blur' }],
    icon_url: [{ required: true, message: '请上传服务图片',trigger: 'change' }],
    parent_id: [{ required: true, message: '请选择服务分类', trigger: 'blur' }],
    service: [{ required: true, validator:checkService, trigger: 'change' }],
  },
});
const serviceTips={
  service_name:'请输入服务名称',
  // service_code:'请输入拼音码',
  // bar_code:'请输入或生成条形码',
  retail_price:'请输入零售价',
  // vip_price:'请输入会员价',
  // service_time:'请输入服务时长',
  // contail_goods:'请选择包含商品',
}
function checkService (rule, value, callback){
  if (value && value.length<=0) {
    return callback(new Error('需要至少添加一项服务'))
  }else{
    let keyArr = Object.keys(serviceTips)
    let key
    let findVal = value.find(item=>keyArr.find(k=>{
      if(item[k] === '') key = k
      return item[k] === ''
    }))
    if(findVal){
      // console.log('service_name',findVal)
      return callback(new Error('请完善服务信息！' + serviceTips[key]))
    }
  }
  callback()
}
// 初始化数据
const tree_id = ref(0)
const treeRef = ref(null);
// ——————————————————————————————————
const defaultProps = {
  children: 'children',
  label: 'tree_id',
};
let nowServiceId = ''
function addGoods(data) {
  let ids = data.contail_goods.split(',').map(id=>Number(id)).filter(id=>id)
    useModal(
        GoodsSelect,
        {
          title: '选择商品',
          multiple: true,
          max: 10,
          ids:ids,
        },
        {
          confirm: (res) => {
            let findData = form.model.service.find(s=>s.shop_type_id == data.shop_type_id)
            findData.contail_goods = res.data.map(item=>item.id).join(',')

          },
        },
      );
    
  }
  function lookGoods(data) {
    console.log('data',data)
    useModal(
      selectLook,
        {
          title: '查看已选',
          ids:data.contail_goods,
        },
        {
          confirm: (res) => {
            let findData = form.model.service.find(s=>s.shop_type_id == data.shop_type_id)
            findData.contail_goods = res.data.map(item=>item.id).join(',')

          },
        },
      );
    
  }

async function getService() {
    let { data, error } = await api.service.getService(route.query.id)
    if (error == 0) {
      console.log('getService',data)
      form.model = cloneDeep(data.attrInfo)
      delete form.model.update_time
      delete form.model.create_time
      delete form.model.delete_time
      form.model.service.forEach(item=>{
        delete item.update_time
        delete item.create_time
        delete item.delete_time
      })
    }
}
async function getTypeList() {
    let { data, error } = await api.service.typeList()
    if (error == 0) {
      options.value = data
    }
}
//添加一级分类
const addfirst = () => {
  form.model.service.unshift({
    tree_id: 'new' + (tree_id.value++),
    service_name: '',
    service_code: '',
    shop_type_id: '',
    bar_code: '',
    retail_price: '',
    vip_price: '',
    service_time: '',
    contail_goods: '',
  });
};
//删除分类
const remove = (node, data) => {
  const parent = node.parent;
  const children = parent.data.children || parent.data;
  const index = children.findIndex((d) => d.tree_id == data.tree_id);
  children.splice(index, 1)
  form.model.service = [...form.model.service]
};

// 表单关闭时提交
function confirm() {
  unref(formRef).validate(async (valid) => {
    if (!valid) return;
    let formRef = cloneDeep(form.model)
    console.log('表单验证通过',formRef)
    let res = route.query.type == 'add' ? 
      await api.service.addService({types:formRef}) : 
      await api.service.setService(route.query.id,{types:formRef})
    if(res.error==0){
      ElMessage({
        message: '操作成功！',
        type: 'success',
      })
      router.back()
    }
  });
}
</script>

<style scoped lang="scss">

::v-deep{
  .el-button{
    margin-left:0 !important;
    border-radius: 40px;
    height: 35px;
  }
}
a {
  cursor: pointer;
}

.service-addbtn{
  position: relative;
  height: 20px;
  left: 140px;
  top: -36px;
}
//分类列表
.custom-tree-header {
  width: 100%;

  .custom-tree-box {
    flex: 1;
    position: unset;
    height: 40px;
    background: var(--sa-table-header-bg);
    font-size: 12px;
    font-weight: 500;
    &>div{
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
}

.type-img {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.head {
  // width: 100%;
  // height: 60px;
  // // background: var(--sa-table-header-bg);
  // padding: 0 16px;

  .des {
    color: var(--sa-subtitle);
    font-size: 14px;
    font-weight: 500;
  }

  .btn {
    color: #806af6;
    font-size: 12px;
  }
}

.drag-item {
  width: 100%;
  height: 100px;
  &>div{
    display: flex;
    align-items: center;
    justify-content: center;
  }
}

.expanded-width-id {
  width: 40px;
  padding-left: 16px;
}

.expanded-width-txm {
  width: 240px;
}
.expanded-width-xm {
  width: 240px;
}
.expanded-width-pym {
  width: 240px;
}
.expanded-width-lsj {
  width: 200px;
}
.expanded-width-hyj {
  width: 200px;
}


.icon-image {
  box-sizing: border-box;
  margin: 10px;
}

.expanded-width-des {
  width: 180px;
}

.expanded-width-sort {
  width: 140px;
}

.expanded-width-operation {
  width: 140px;
}

.expanded-width-id,
.expanded-width-input,
.expanded-width-image,
.expanded-width-des,
.expanded-width-sort,
.expanded-width-operation {
  flex-shrink: 0;
}


:deep() {
  .el-radio-button__inner {
    padding: 0;
    border: none;
  }

  .el-popover.el-popper {
    padding: 8px;
  }

  .el-tree-node__content {
    width: 100%;
    height: 100%;
  }

  .el-tree-node__expand-icon {
    display: none;
  }

  .el-tree-node__content {
    padding-left: 0 !important;
  }

  .card-item {
    position: relative;
    overflow: hidden;
    width: 32px !important;
    height: 32px !important;
    color: var(--sa-subtitle);
    border: 1px solid var(--sa-border);
    border-radius: 4px;

    .image-overlay {
      width: 32px !important;
      height: 32px !important;
      position: absolute;
      top: 0;
      left: 0;
      background: var(--sa-basic-mask-background);
      color: var(--sa-basic-mask-color);
      display: none;

      i {
        font-size: 16px;
        cursor: pointer;
      }
    }

    &:hover {
      .image-overlay {
        display: flex;
      }
    }
  }

  .upload-icon {
    width: 32px !important;
    height: 32px !important;
    background: var(--sa-background-assist);
    border: 1px dashed var(--sa-border);
    border-radius: 4px;
    cursor: pointer;

    i {
      color: var(--sa-place);
      font-size: 14px !important;
    }
  }
}

.el-tree {
  flex: 1;
  position: unset;
}

.append-title {
  color: var(--el-color-primary);
}

.category-style {
  margin-right: 24px;
}

.category-image {
  width: 78px;
  height: 124px;
  display: flex;
  position: relative;
  border-radius: 4px;
}

.activeBorder {
  border: 1px solid var(--el-color-primary);
}

.badge {
  color: var(--el-color-primary);
  width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
  border-radius: 50%;
  font-weight: 600;
  font-size: 14px;
  position: absolute;
  top: -8px;
  right: -8px;
}

.category-title {
  font-size: 12px;
  line-height: 14px;
  color: var(--sa-font);
  margin-right: 4px;
  margin-top: 8px;
}

.hover-img {
  width: 220px;
  height: 350px;
  display: flex;
}

.category-icon {
  width: 14px;
  height: 14px;
  margin-top: 8px;
}
</style>